package com.shareach.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;
import com.shareach.common.BaseQueryOrder;
import com.shareach.dao.redis.impl.DeployRDao;
import com.shareach.dao.redis.impl.DeployRDao.DeployType;
import com.shareach.domain.BizCardDomain;
import com.shareach.service.BaseCityService;
import com.shareach.service.BaseShopService;
import com.shareach.service.BizCardService;
import com.shareach.util.JsonUtil;
import com.shareach.web.basic.Answer;

@Controller("wcard")
@RequestMapping("/wcard")
public class CardController extends BaseController {

	@Autowired
	BaseShopService shopService;
	@Autowired
	BaseCityService cityService;
	@Autowired
	private DeployRDao deployRDao;
	@Autowired
	private BizCardService cardService;

	@RequestMapping(value = "/index.htm")
	public ModelAndView index(HttpServletRequest request, String shopName, Long cityId, Long id, String title,
			Integer hasdeploy, Integer hasmatch) {
		ModelAndView mv = new ModelAndView("admin/discount/card/index");
		BizCardDomain domain = new BizCardDomain();

		BaseQueryOrder order = new BaseQueryOrder();
		order.setNumber(getPageNo(request).toString());
		order.setPageSize(getPageSize(request));
		order.addSort("_id", Order.DESCENDING.toString());
		addCriteria(domain, hasdeploy, "deployTime");
		addCriteria(domain, hasmatch, "shopId");
		Map<String, Object> conditions = Maps.newHashMap();

		if (null != cityId) {
			conditions.put("cityId", cityId);
			domain.setCity(cityId);
		}
		if (null != id) {
			domain.setId(id);
		}
		if (StringUtils.isNotEmpty(shopName)) {
			domain.addRegexMap(shopName.trim(), new String[] { "name", "brandName", "orgName" });
			conditions.put("shopName", shopName.trim());
		}

		if (StringUtils.isNotEmpty(title)) {
			domain.addRegexMap(title, "title");
			conditions.put("title", title);
		}
		Page<BizCardDomain> cards = cardService.getPageResult(domain, order);
		List<BizCardDomain> cardList = cards.getContent();
		for (BizCardDomain bizCard : cardList) {
			if (bizCard.getShopId() != null && bizCard.getShopId() > 0) {
				bizCard.setBaseShop(shopService.getById(bizCard.getShopId()));
			}
		}
		mv.addObject("cities", cityService.findAll());
		mv.addObject("result", cards);
		mv.addObject("conditions", conditions);
		mv.addObject("id", id);
		mv.addObject("deploy", hasdeploy);
		mv.addObject("match", hasmatch);
		return mv;
	}

	@RequestMapping(value = "/edit.htm")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, String cardId,
			BizCardDomain domain) {
		ModelAndView view = new ModelAndView("admin/discount/card/edit");
		if (domain == null || domain.getId() == null) {
			// redirect
			Long parabrand = Long.valueOf(cardId);
			BizCardDomain card = cardService.getById(parabrand);
			view.addObject("card", card);
			return view;
		} else {
			Answer<Object> r = new Answer<Object>();
			try {
				BizCardDomain tuan = cardService.getById(domain.getId());
				BizCardDomain change = tuan.compareTo(domain);
				change.setId(domain.getId());
				// edit
				cardService.update(change);
				// update redis
				resetRedisDeployed(DeployType.Card, domain.getId());
				this.outText(response, JsonUtil.jsonFromObject(r));
			} catch (Exception e) {
				r.setCode(-1);
				r.setMsg("System Error");
				this.outText(response, JsonUtil.jsonFromObject(r));
				e.printStackTrace();
			}
		}
		return view;
	}

	private void addCriteria(BizCardDomain domain, Integer val, String propName) {
		if (null == val) {
			return;
		}
		switch (val) {
		case 2:
			domain.addFieldExists(propName);
			break;
		case 3:
			domain.addFieldNoneExists(propName);
			break;
		}
	}

	public void resetRedisDeployed(DeployType type, Long id) {
		if (deployRDao.isDeployed(type, id)) {
			deployRDao.setUndeployed(type, id);
		}
	}

}
